const router = require('express').Router();
const { dbQuery, dbError, sqlStrQuotationHandle } = require('../../tools');

router.get('/account', function(req, res) {
	const {acc} = req.query;
	const accStr = sqlStrQuotationHandle(acc);
	dbQuery(`select * from user_table where binary account='${accStr}'`)
	.then(data => {
		if (data.length < 1) {
			res.send({code: 1, message: '账号可以使用'});
			return;
		}
		res.send({code: 0, message: '账号已被占用'});
	})
	.catch(err => {
		dbError(res, err);
	});
});
router.get('/group', function(req, res) {
	const {user_id, group_id} = req.query;
	
	Promise.all([
		dbQuery(`select admin, creator_id from group_table where group_id='${group_id}'`),
		dbQuery(`select user_id from member_table where group_id='${group_id}'`)
	])
	.then(data => {
		const members = data[1].map(val => val.user_id);
		const admins = data[0][0].admin.split(',').map(val => +val);
		const creator = data[0][0].creator_id;
		if (creator === +user_id) {
			res.send({code: 4, message: '成功'});
		} else if (admins.includes(+user_id)) {
			res.send({code: 3, message: '成功'});
		} else if (members.includes(+user_id)) {
			res.send({code: 2, message: '成功'});
		} else {
			res.send({code: 1, message: '成功'});
		}
	})
	.catch(err => {
		dbError(res, err);
	})
});


module.exports = router;